package org.acme.hibernate.orm.panache;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.ext.Provider;
import org.jboss.resteasy.reactive.client.spi.ResteasyReactiveClientRequestContext;
import org.jboss.resteasy.reactive.client.spi.ResteasyReactiveClientRequestFilter;

import java.net.URI;
import java.util.List;

@Provider
public class MyClientRequestFilter implements ResteasyReactiveClientRequestFilter {

    @Inject
    NamingService namingService;

    @Override
    public void filter(ResteasyReactiveClientRequestContext requestContext) {

        URI uri = requestContext.getUri();

        String host = uri.getHost();
        if (!Constant.NACOS_INSTANCE_MAP.containsKey(host)) {
            try {
                List<Instance> allInstances = namingService.getAllInstances(host);
                Constant.NACOS_INSTANCE_MAP.put(host, allInstances);
            } catch (NacosException e) {
                throw new RuntimeException(e);
            }
        }

        if (Constant.NACOS_INSTANCE_MAP.containsKey(host)) {
            List<Instance> instances = Constant.NACOS_INSTANCE_MAP.get(host);
            if (!instances.isEmpty()) {
                // 随机获取一个元素
                Instance instance = instances.get(0);
                requestContext.setUri(URI.create(uri.getScheme() + "://" + instance.getIp() + ":" + instance.getPort() + uri.getPath()));
            }
        }
    }
}
